import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import '../model/order_request_data.dart';
import '../net/apis.dart';
import '../net/net_response/menu/regular_menu_data.dart';
import '../saas_order_meal.dart';
import '../viewmodel/regular_menu_contain_view_model.dart';
import '../widget/select_item_widget.dart';

class FoodMenuContainerWidget extends BaseStatefulMvvmWidget {
  List<RegularMenuData> menuList;
  final OrderRequestData orderData;
  final bool isRegular;
  final String? date;
  OnFoodSelectListener? selectListener;

  FoodMenuContainerWidget(
      {required this.menuList,
      required this.orderData,
      this.isRegular = false,
      this.date,
      this.selectListener});

  @override
  State<StatefulWidget> createState() => _FoodMenuContainWidget();
}

class _FoodMenuContainWidget extends BaseMvvmState<RegularMenuContainViewModel,
    FoodMenuContainerWidget> {
  @override
  Widget? buildLoadingContentView() {
    return Row(
      children: [
        SelectItemWidget<RegularMenuData>(
          viewModel.menuList,
          position: viewModel.timeSelection,
          canSelected: (item) {
            return "";
            // return item.hasOrderedRemark.isNotEmpty?item.hasOrderedRemark:item.canSelectRemark??"";
          },
          itemBuilder: (context, item, index, selected) {
            return LeftTimeTypeItemWidget(item, selected);
          },
          onCallback: (index, data) {
            setState(() {
              viewModel.timeSelection = index;
              viewModel.selectTime = data;
            });
          },
          separatorBuilder: (context, index) {
            return const SizedBox(
              height: 20,
            );
          },
          padding: EdgeInsets.symmetric(vertical: 30),
        ).addToContainer(
            width: 70, margin: EdgeInsets.symmetric(horizontal: 16)),
        ListView(
          padding: EdgeInsets.symmetric(vertical: 20),
          children: (viewModel.selectTime?.timeSectionList ?? []).map((e) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if ((e.categaryList ?? []).isNotEmpty && !widget.isRegular) ...[
                  CommonText("${e.categary} 选${e.selectNumber}"),
                  Container(
                    height: 15,
                  )
                ],
                ListView(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  children: (e.categaryList ?? [])
                      .map((food) => itemMenuContent(e, food))
                      .toList(),
                )
              ],
            );
          }).toList(),
        ).setWeight(3),
        Container(
          width: 16,
        )
      ],
    );
  }

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return loadingContentWidget;
  }

  Widget itemMenuContent(
      RegularMenuTimeSectionList data, RegularMenuCategaryList food) {
    return Stack(
      children: [
        Stack(
          children: [
            CachedNetworkImage(
              imageUrl: "${Apis.imageHead}${food.attachIds}",
              width: 90,
              height: 90,
              httpHeaders: ImageLoad.globalHeader,
              placeholder: (context, url) {
                return SaasOrderMeal.foodImagePlaceHold==null?Image.asset(
                  "images/none.png",
                  package: "saas_order_meal",
                  width: 90,
                  height: 90,
                ):Image.asset(
                  SaasOrderMeal.foodImagePlaceHold!,
                  width: 90,
                  height: 90,
                );
              },
              errorWidget: (context, url, error) {
                return SaasOrderMeal.foodImagePlaceHold==null?Image.asset(
                  "images/none.png",
                  package: "saas_order_meal",
                  width: 90,
                  height: 90,
                ):Image.asset(
                  SaasOrderMeal.foodImagePlaceHold!,
                  width: 90,
                  height: 90,
                );
              },
            ).onTap(() {
              addTap(data, food);
            }),
            CommonText(food.goodsName).setLocation(left: 100, top: 4),
            CommonText("¥${food.price}", textColor: Colors.red)
                .setLocation(bottom: 4, left: 100),
            if (!SaasOrderMeal.canChooseMore && !widget.isRegular)
              Row(
                children: [
                  if ((food.status ?? 0) == 1)
                    Icon(
                      Icons.check_circle,
                      color: SaasOrderMeal.mainColor,
                      size: 30,
                    )
                ],
              ).setLocation(bottom: 0, right: 0),
            if (SaasOrderMeal.canChooseMore || widget.isRegular)
              Row(
                children: [
                  if ((food.number ?? 0) > 0)
                    Icon(
                      Icons.remove_circle_outline,
                      color: SaasOrderMeal.mainColor,
                      size: 30,
                    ).onTap(() {
                      viewModel.removeClick(food);
                    }),
                  Container(
                    width: 15,
                  ),
                  if ((food.number ?? 0) > 0)
                    CommonText("${food.number ?? 0}", textSize: 20),
                  Container(
                    width: 15,
                  ),
                  Icon(
                    Icons.add_circle_rounded,
                    color: SaasOrderMeal.mainColor,
                    size: 30,
                  ).onTap(() async {
                    if (SaasOrderMeal.checkOldTag) {
                      var result = await viewModel.checkTags(food);
                      if (result) {
                        viewModel.addClick(food, data);
                      }
                    } else {
                      viewModel.addClick(food, data);

                    }
                  })
                ],
              ).setLocation(bottom: 0, right: 0),
          ],
        ).onTap(() {
          if (!SaasOrderMeal.canChooseMore && !widget.isRegular) {
            addTap(data, food);
          }
        }).addToContainer(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: 10.borderRadius)),
        if (!food.disableRemark.isNullOrEmpty())
          Container(
            decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.5),
                borderRadius: 10.borderRadius),
          ).onTap(() {
            if (!food.disableRemark.isNullOrEmpty()) {
              showToast(food.disableRemark);
              return;
            }
          }).setLocation(left: 0, right: 0, top: 0, bottom: 0)
      ],
    ).addToContainer(
      margin: EdgeInsets.only(bottom: 10),
    );
  }

  @override
  RegularMenuContainViewModel createViewModel() {
    return RegularMenuContainViewModel(context,
        menuList: widget.menuList,
        orderData: widget.orderData,
        isRegular: widget.isRegular,
        date: widget.date,
        selectListener: widget.selectListener);
  }

  Future<void> addTap(
      RegularMenuTimeSectionList data, RegularMenuCategaryList food) async {
    if (!food.disableRemark.isNullOrEmpty()) {
      showToast(food.disableRemark);
      return;
    }
    if (SaasOrderMeal.canChooseMore || widget.isRegular) {
      if (SaasOrderMeal.checkOldTag) {
        var result = await viewModel.checkTags(food);
        if (result) {
          viewModel.addClick(food, data);
        }
      } else {
        viewModel.addClick(food, data);
      }
      return;
    }
    setState(() {
      viewModel.multiChooseClick(food, data);
      viewModel.getSelectItem();
    });
  }

  @override
  void onRetryClick() {}
}
